package app.r_teenus.frontend.controller;


import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.springframework.binding.message.MessageBuilder;
import org.springframework.binding.message.MessageContext;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import app.r_teenus.backend.model.Contact;


@Component
public class ContactValidator {

	/**
	 * Spring Web Flow activated validation (validate + ${state}). Validates 'personForm' view state after binding to person.
	 */
	public void validateContactForm(Contact contact, MessageContext context) {
		if (StringUtils.hasText(contact.getValueText())) {
			if (contact.getContactTypeId() == 1) {
				String expression = "^[\\w\\-]([\\.\\w])+[\\w]+@([\\w\\-]+\\.)+[A-Z]{2,4}$";
				CharSequence inputStr = contact.getValueText();
				Pattern pattern = Pattern.compile(expression, Pattern.CASE_INSENSITIVE);
				Matcher matcher = pattern.matcher(inputStr);
				if (!matcher.matches()) {
					context.addMessage(new MessageBuilder().error().source("valueText").code("contact.form.valueText.email.error").build());
				}
			} else {
				String expression = "(\\(?(\\d{3})\\))?(\\d{2}-)?(\\d{1}-)?(\\d{5})";
				CharSequence inputStr = contact.getValueText();
				Pattern pattern = Pattern.compile(expression);
				Matcher matcher = pattern.matcher(inputStr);
				if (!matcher.matches()) {
					context.addMessage(new MessageBuilder().error().source("valueText").code("contact.form.valueText.phoneNumber.error").build());
				}
			}
		} else {
			context.addMessage(new MessageBuilder().error().source("valueText").code("contact.form.valueText.required").build());
		}
	}
}
